package com.cjd.common.utils

import android.app.Activity
import android.app.AlertDialog
import android.view.Gravity
import android.view.View
import android.widget.Toast

/**
 * <pre>
 *     author : chenjidong
 *     e-mail : chenjidong@guangxirenrenparking.com
 *     time   : 2020/04/03
 *     desc   : 自定义扩展工具包
 *     version: 1.0.0
 * </pre>
 */
/**
 * 判断对象/Collection 是否为null 或者空
 * @param block lambda 表达式
 */
fun <T> T.isNull(block: () -> Unit) {
    if (this == null || (this is Collection<*> && this.isEmpty()) || (this is String && "" == this))
        block.invoke()
}

/**
 * 判断对象/Collection 不为null 或者空
 * @param block lambda 表达式
 */
fun <T> T.isNotNull(block: (T) -> Unit) {
    if (this != null && this is Collection<*>) {
        if (this.isNotEmpty())
            block.invoke(this)
    } else if (this != null && this is String) {
        if ("" != this)
            block.invoke(this)
    } else if (this != null)
        block.invoke(this)
}

/**
 * 快捷隐藏或显示view
 */
var View.hide: Boolean
    get() = this.visibility == View.GONE
    set(value) {
        if (value) this.visibility = View.GONE else this.visibility = View.VISIBLE
    }

/**
 * 自定义封装 toast
 * @param resId 资源id
 * @param msg 字符串
 * @param duration 显示时间  单位：ms
 * @param gravity 显示位置 默认居中 非 Gravity.NO_GRAVITY 时可用
 * @param xOffset x 轴偏移
 * @param yOffset y 轴偏移
 */
fun Activity.showToast(
    resId: Int = 0,
    msg: CharSequence? = "",
    duration: Int = Toast.LENGTH_LONG,
    gravity: Int = Gravity.NO_GRAVITY,
    xOffset: Int = 0,
    yOffset: Int = 0
) {
    val toast = if (resId > 0) Toast.makeText(this, resId, duration)
    else Toast.makeText(this, msg ?: "", duration)
    if (gravity != Gravity.NO_GRAVITY)
        toast.setGravity(gravity, xOffset, yOffset)
    toast.show()
}

/**
 * 快捷显示默认dialog
 * @param message 标题
 * @param negativeMsg 左边文案
 * @param positiveMsg 有别文案
 */
fun Activity.showAlertDialog(
    message: String?,
    negativeMsg: String? = "取消",
    positiveMsg: String? = "确定",
    callback: ((isAgree: Boolean) -> Unit)? = null
) {
    AlertDialog.Builder(this)
        .setMessage(message)
        .setNegativeButton(negativeMsg) { dialog, which ->
            dialog.dismiss()
            callback?.invoke(false)
        }.setPositiveButton(positiveMsg) { dialog, which ->
            dialog.dismiss()
            callback?.invoke(true)
        }.create().show()
}